package com.hunlian.makelove.update;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Environment;
import android.os.IBinder;

import com.hunlian.makelove.update.AppDownloadIntentService.MyBinder;


public class AppDownloadManager {

	private Context mContext;
	private AppDownloadManager mInstance;
	public boolean notificationTag = false;
	private AppDownloadIntentService mService;
	private AppDownloadManager mSelf;
	
	public AppDownloadManager(Context context) {
		mContext = context;
		AppDownloadIntentService.canDownload = true;
		mSelf = this;
	}

	
	/**检查是否装载sd卡*/
	public static boolean isSDcardCanRead$Write(){
		String sdCardState = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(sdCardState)) {
			return true;
		}
		return false;
	}
	
	/**开始下载*/
	public void startDownload(String url,String apkName) {
		Intent intent = new Intent(mContext, AppDownloadIntentService.class);
		intent.putExtra("url", url);
		intent.putExtra("apkName", apkName);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		//System.out.println("开启后台下载服务");
		mContext.bindService(intent, conn, Context.BIND_AUTO_CREATE);
		mContext.startService(intent);	
	}
	
	/**停止下载**/
	public void stopDownload(){
		if(mService!=null){
			mService.isStopDownload = true;
		}
		
		//mContext.unbindService(conn);
		/**
		 * 如果启动的是IntentService,stopService(intent)不会关闭掉Service的；
		 * IntentService中的任务是在一个单独的线程中
		 * 执行，任务执行完后，系统会去关闭Service
		 */
/*		Intent intent = new Intent(mContext, AppDownloadIntentService.class);
		mContext.stopService(intent);*/
		
		AppDownloadIntentService.canDownload = false;
	}
	
	public void unboundService(){
		mContext.unbindService(conn);
		if(mService!=null){
			mService.setAppDownloadManager(null);
		}
	}
	
	
	private ServiceConnection conn = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			//System.out.println("绑定成功：---onServiceConnected---");
			MyBinder binder = (MyBinder) service;
			mService = binder.getService();
			mService.setAppDownloadManager(mSelf);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			//System.out.println("绑定失败：---onServiceDisconnected---");
		}
		
	};
	
	
	/**
	 * 在通知栏显示进度
	 */
	public void showNotification(){
		
		
		if(mService!=null){
			mService.createNotification();
			mService.startOnce = false;
			mService.isShowNotification = true;
			notificationTag = true;
			//System.out.println(mService+"调用显示通知下载进度栏,myService不为空"+mService.isShowNotification);
		}else{
			//System.out.println("调用显示通知下载进度栏,myService为空");
		}
	}
	
	public void clearNotification(){
		if(mService!=null){
			mService.clearNotification();
		}
	}

}
